const PARENT_KEY = 'FID'
const KEY = 'ID'
const TITLE_KEY = '名字'
const ROUTE_KEY = '路由'
const PATHS = [
  { key: '1', path: '/home' },
  { key: '59', path: '/approval' },
  { key: '5', path: '/manage' },
  { key: '6', path: '/dataSource' },
  { key: '8', path: '/system' }
]
/**
 * 
 * @param {目录信息} list 
 * @returns 转换后的父子级数据
 */
export const transRoutes = (list = []) => {
  const parent = list.filter(item => item[PARENT_KEY] === '0')
  transByParent(parent, list)
  return parent
}

const transByParent = (parent, list) => {
  parent.map(p => {
    p.title = p[TITLE_KEY]
    p.isHovering = false
    p.key = p[KEY]
    const path = p[ROUTE_KEY]
    const children = transListToTreeData(list, p[KEY], path)
    p.children = children
  })
}

const transListToTreeData = (list, rootValue, path) => {
  // 思路：先找到所有的根节点，然后再再去添加children，第二个参数是根节点的pid值
  var arr = []
  list.forEach((item) => {
    if (item[PARENT_KEY] === rootValue) {
      item.title = item[TITLE_KEY]
      item.isHovering = false
      item.key = `${rootValue}-${item[KEY]}`
      item.path = path
      const children = transListToTreeData(list, item[KEY], path)
      if (children.length) {
        // 如果children的长度大于0就说明找到了子节点
        item.children = children
      }
      arr.push(item)
    }
  })
  return arr
}


export const searchRoutes = (list, value) => {
  const searchVal = value.toLowerCase()
  const parentHasVal = list.filter(item => item['名字'].toLowerCase().indexOf(searchVal) !== -1)
  if (parentHasVal.length > 0) {
    return parentHasVal
  } else {
    const arr = []
    list.map(line => {
      if (line.children && line.children.length > 0) {
        const childList = []
        searchChild(line.children, searchVal, childList)
        if (childList.length > 0) {
          arr.push({ ...line, children: childList })
        }
      }
    })
    return arr
  }
}
const searchChild = (list, searchVal, arr, parentLine) => {
  list.map(line => {
    if (line['名字'].toLowerCase().indexOf(searchVal) !== -1) {
      if (parentLine) {
        arr.push({ ...parentLine, children: [line] })
      } else {
        arr.push(line)
      }
    } else {
      if (line.children && line.children.length > 0) {
        searchChild(line.children, searchVal, arr, line)
      }
    }
  })
}